import { AddOrderItemType, CreateOrderParamType, GetOrderListParamType } from "@Tea/model"
import { AppTokenObj } from "../dao/AppToken"
import { OrderItemRepository } from "../repo/OrderItemRepository"
import { OrderRepository } from "../repo/OrderRepository"

export class OrderContext {
  private static inst: OrderContext
  private orderRepo: OrderRepository = OrderRepository.getInstance()
  private orderItemRepo: OrderItemRepository = OrderItemRepository.getInstance()

  public static getInstance() {
    if (!OrderContext.inst) {
      OrderContext.inst = new OrderContext()
    }

    return OrderContext.inst
  }

  createOrder(customer: AppTokenObj['userId'], address: CreateOrderParamType["address"]) {
    return this.orderRepo.createOrder(customer, address)
  }

  // 创建订单时追加商品
  addOrderItem(params: AddOrderItemType) {
    return this.orderItemRepo.addOrderItem(params)
  }

  cancelOrder(orderId: string) {
    return this.orderRepo.cancelOrder(orderId)
  }

  cancelOrderItem(orderId: string) {
    return this.orderItemRepo.cancelOrderItem(orderId)
  }

  pay(orderId: string) {
    return this.orderRepo.pay(orderId)
  }

  confirm(orderId: string) {
    return this.orderRepo.confirm(orderId)
  }

  async orderList(params: GetOrderListParamType, customer: AppTokenObj['userId']) {
    const orderNotItemList = (await this.orderRepo.orderList(params.state, customer))[0]

    console.log('orderNotItemList', orderNotItemList);


    const itemList = await Promise.all(
      orderNotItemList.map(o => this.orderItemRepo.getItemByOrderId(o.orderId))
    )

    itemList.forEach((item, index) => {
      orderNotItemList[index].itemList = item[0]
    })

    return orderNotItemList
  }
}